<template>
  <div class="setting-main">
    <el-tree
      v-loading="addLoading"
      :data="fieldItems"
      :props="defaultProps"
      :default-expanded-keys="defaultExpandedKeys"
      :expand-on-click-node="true"
      :draggable="true"
      :allow-drop="allowDrop"
      :allow-drag="allowDrag"
      node-key="pid"
      @node-drop="handleDrop">
      <div slot-scope="{ node, data }" class="custom-tree-node">
        <div class="expend-btn">
          <img v-if="!node.isLeaf && !node.expanded" :src="expend" class="expend-icon" alt="">
          <img v-if="!node.isLeaf && node.expanded" :src="expend_active" class="expend-icon" alt="">
          <img v-if="node.isLeaf" :src="expend_active_no" class="expend-icon" alt="">
        </div>
        <div v-if="!data.nodeActionType" :class="node.level !== 1 && 'is-draggable'" class="tree-main">
          <div v-if="node.level === 1" class="flex-center">
            {{ node.label }}<InfoIcon style="margin-left: 6px" content="从上往下，客户等级由高到低" />
          </div>
          <div v-else class="tree-content">
            <div class="tree-content-cell">
              <span class="label-text">等级名称：</span>
              <el-tooltip :open-delay="800" placement="top" style="margin-right: 6px;">
                <div slot="content" style="max-width:200px;">
                  {{ data.name }}
                </div>
                <div :style="{color: data.color || '#333', background: data.color ? changeColorAlphaVal(data.color, 0.14) : 'transparent'}" class="level-name-bg ellipsisOne">{{ data.name || '--' }}</div>
              </el-tooltip>
            </div>
            <div class="tree-content-cell"><span class="label-text">总欠款额度：</span>
              <el-tooltip :open-delay="800" placement="top">
                <div slot="content" style="max-width:200px;">
                  {{ data.levelAmount | moneyFilter(true, '', true) }}
                </div>
                <div>{{ data.levelAmount | bigDataFilter(true, '', true) }}</div>
              </el-tooltip>
            </div>
            <div class="tree-content-cell"><span class="label-text">欠款账期：</span>{{ data.levelTimeLimit }}天</div>
            <div class="tree-content-cell"><span class="label-text">可选择岗位：</span>
              <ToolTip :content="data.levelPost | postToString" style="max-width: calc(100% - 90px)"/>
            </div>
            <div class="tree-content-cell flex-center"><span class="label-text">是否扣除：</span>{{ data.levelIsDeduct === 1 ? '是' : '否' }}
              <el-tooltip placement="top">
                <div slot="content">控制新建编辑导入渠道订单扣除销售额度，与扣除客户额度无关</div>
                <tipIcon is-diy class="ml5 tip"/>
              </el-tooltip>
            </div>
            <div class="tree-content-cell"><span class="label-text">是否默认：</span>{{ data.isDefault ? '是' : '否' }}</div>

          </div>
        </div>
        <!-- 新增/编辑 -->
        <div v-if="data.nodeActionType" class="tree-main" @click.prevent.stop="() => {}">
          <div class="tree-content">
            <div class="tree-content-cell">
              <span class="label-text mr5">等级名称</span>
              <el-input v-model="data.name" :maxlength="10" size="small" class="auto-width-input" placeholder="请输入">
                <el-color-picker
                  slot="suffix"
                  v-model="data.color"
                  show-alpha
                  color-format="rgb"
                  size="small"
                  style="margin-right: -5px"/>
              </el-input>
            </div>
            <div class="tree-content-cell">
              <span class="label-text mr5">总欠款额度</span>
              <el-input
                v-model.trim="data.levelAmount"
                oninput="if(value>999999999)value=999999999;if(value<0)value=0;"
                type="number"
                placeholder="请输入"
                size="small"
                class="auto-width-input"
                @mousewheel.native.prevent />
            </div>
            <div class="tree-content-cell">
              <span class="label-text mr5">欠款账期</span>
              <el-input
                v-model.trim="data.levelTimeLimit"
                oninput="if(value>1000)value=1000;value=value.replace(/^0+(\d)/,'$1')"
                type="number"
                placeholder="请输入"
                size="small"
                class="cell-input"
                @mousewheel.native.prevent>
                <span slot="suffix" style="margin-right:5px;color:#333;">天</span>
              </el-input>
            </div>
            <div class="tree-content-cell width-240">
              <span class="label-text mr5">可选择岗位</span>
              <SelectWithUserLoad
                ref="selectUser"
                v-model="data.levelPost"
                :hide-select-list="data.levelPost || []"
                :default-list="defaultLevelPost || []"
                :loadmore-method="queryAllPost()"
                value-type="object"
                style="width: 160px;"
                placeholder="请选择"
                class="post-select"
                key-name="id"
                label-name="name"
                multiple
                filterable
                collapse-tags
                clearable
              />
            </div>
            <div class="tree-content-cell">
              <span class="label-text mr5">是否扣除</span>
              <el-select
                v-model="data.levelIsDeduct"
                size="small"
                placeholder="请选择"
                class="cell-input"
                popper-class="global-select-down">
                <el-option
                  v-for="item in deductOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"/>
              </el-select>
            </div>

            <div class="tree-content-cell">
              <span class="label-text mr5">是否默认</span>
              <el-switch
                v-model="data.isDefault"
                class="fb-switch"
              />
            </div>
          </div>
        </div>
        <div v-if="node.level === 1" class="setting-btn-container">
          <div class="btn" @click.prevent.stop="toAddSetting(node, data)">添加</div>
        </div>
        <div v-else class="setting-btn-container" @click.prevent.stop="() => {}">
          <template v-if="data.nodeActionType">
            <div class="btn" @click.prevent.stop="httpStore(node, data)">保存</div>
            <div class="btn cancel-btn" @click.prevent.stop="handleCancel(node, data)">取消</div>
          </template>
          <template v-else>
            <div v-if="node.level === 2" class="btn" @click.prevent.stop="toEditSetting(data)">编辑</div>
            <div v-if="node.level === 2" class="btn" @click.prevent.stop="deleteSetting(node,data)">删除</div>
          </template>
        </div>
      </div>
    </el-tree>
  </div>
</template>
<script>
import SelectWithUserLoad from '@/components/Common/selectWithUserLoad';
import { getAllPost } from '@/api/user';
import { deleteSetting, editSetting, addSetting, customerLevelSort } from '@/api/setting';
import { moneyFilter, bigDataFilter } from '@/filters/number';
import { hasRouteAuth } from '@/utils/permission';
import { showModal } from '@/utils/message';
import { changeColorAlphaVal } from '@/utils/tools';
import expend from '@/assets/setting/expend.png';
import expend_active from '@/assets/setting/expend-active.png';
import expend_active_no from '@/assets/setting/expend-active_no.png';

export default {
  components: {
    SelectWithUserLoad
  },
  filters: {
    moneyFilter,
    bigDataFilter,
    postToString(arr) {
      if (Array.isArray(arr)) return arr.map(i => i.name).join() || '无限制';
      return arr || '无限制';
    }
  },
  props: {
    fieldItems: {
      type: Array,
      default: () => []
    },
    defaultExpandedKeys: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      changeColorAlphaVal,
      expend, expend_active, expend_active_no,
      defaultLevelPost: [],
      addLoading: false,
      defaultProps: {
        children: 'item',
        label: 'name'
      },
      levelOriginalData: null
    };
  },
  computed: {
    deductOptions() {
      return [
        { id: 0, label: '否' },
        { id: 1, label: '是' }
      ];
    },
    // 节点操作类型
    NODE_ACTION_TYPE() {
      return { ADD: 1, EDIT: 2 };
    }
  },
  methods: {
    queryAllPost() {
      return function(params) {
        return new Promise((resolve, reject) => {
          getAllPost(params).then(res => {
            if (res.data && res.data.items) {
              res.data.items = res.data.items.map(name => ({ id: name, name }));
            }
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
    },
    // 判断节点能否被拖拽 Function(node)
    allowDrag(draggingNode) {
      return draggingNode.isLeaf && draggingNode.data.nodeActionType !== this.NODE_ACTION_TYPE.ADD;
    },
    // 拖拽后判定目标节点能否被放置
    allowDrop(draggingNode, dropNode, type) {
      if (draggingNode.level === dropNode.level) {
        // 向上拖拽 || 向下拖拽
        if (dropNode.data.nodeActionType === this.NODE_ACTION_TYPE.ADD) {
          return false;
        }
        return type === 'prev' || type === 'next';
      } else {
        // 不同级进行处理
        return false;
      }
    },
    hasRouteAuth,
    getData(respetPid) {
      this.$emit('getData', respetPid);
    },
    // 新增字段
    toAddSetting(node, data) {
      if (data.item && data.item.length > 0) {
        const hasAddItem = data.item.some(i => i.nodeActionType);
        if (hasAddItem) {
          this.$message.warning('已存在编辑项');
          if (!node.expanded) this.$set(node, 'expanded', true);
          return;
        }
      }
      const newChild = {
        name: '',
        color: '',
        nodeActionType: this.NODE_ACTION_TYPE.ADD,
        levelAmount: null,
        levelTimeLimit: null,
        levelPost: '',
        levelIsDeduct: 0,
        pid: data.pid
      };
      data.item.unshift(newChild);
      this.$nextTick(() => {
        if (!node.expanded) this.$set(node, 'expanded', true);
        this.$forceUpdate();
      });
    },
    // 编辑字段
    toEditSetting(data) {
      if (this.fieldItems[0].item.some(i => i.nodeActionType)) {
        this.$message.warning('已存在编辑项');
        return;
      }
      this.levelOriginalData = _.cloneDeep(data);
      this.defaultLevelPost = data.levelPost;
      this.$set(data, 'nodeActionType', this.NODE_ACTION_TYPE.EDIT);
    },
    // 取消添加/编辑
    handleCancel(node, data) {
      const parent = node.parent;
      const children = parent.data.item || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      if (data.nodeActionType === this.NODE_ACTION_TYPE.ADD) {
        children.splice(index, 1);
      } else if (data.nodeActionType === this.NODE_ACTION_TYPE.EDIT) {
        children.splice(index, 1, this.levelOriginalData);
        this.$forceUpdate();
        this.levelOriginalData = null;
        this.defaultLevelPost = [];
      }
    },
    // 信息校验
    validateLevelInfo(data) {
      return new Promise((resolve, reject) => {
        let isOk = true;
        if (!data.name || (!data.levelAmount && data.levelAmount !== 0) ||
          (!data.levelTimeLimit && data.levelTimeLimit !== 0)) {
          isOk = false;
        }
        if (isOk && !data.color) {
          reject('请选择等级颜色');
          return;
        }
        isOk ? resolve() : reject('请完善客户等级信息');
      });
    },
    // 新增/编辑
    httpStore(node, data) {
      this.validateLevelInfo(data).then(() => {
        const root = this.getRoot(node);
        const params = _.cloneDeep(data);
        params.type = root.data.id;
        if (Array.isArray(params.levelPost)) {
          params.levelPost = params.levelPost.map(i => i.name).join();
        }
        this.addLoading = true;
        const storeApi = data.nodeActionType === this.NODE_ACTION_TYPE.ADD ? addSetting : editSetting;
        storeApi(params).then(res => {
          this.addLoading = false;
          if (res.code === 200) {
            this.$message.success('操作成功');
            delete data.nodeActionType;
            this.levelOriginalData = null;
            this.defaultLevelPost = [];
            this.getData([data.pid]);
          } else {
            this.$message.success(res.message);
          }
        }).catch(() => {
          this.addLoading = false;
        });
      }).catch(err => {
        this.$message.warning(err);
      });
    },
    // 编辑字段 end
    deleteSetting(node, data) {
      showModal('是否确认删除？').then(() => {
        const root = this.getRoot(node);
        const params = {
          type: root.data.id,
          id: data.id
        };
        deleteSetting(params).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功');
            this.getData([node.parent.data.pid]);
          } else {
            this.$message.error(res.message);
          }
        }).catch(err => {
          console.error(err);
        });
      });
    },
    getRoot(node) {
      if (!node) return null;
      if (node.level === 1) {
        return node;
      }
      return this.getRoot(node.parent);
    },
    // 拖动
    handleDrop(draggingNode, dropNode) {
      const params = {
        sortArr: this.fieldItems[0].item
      };
      let respetPid = [];
      if (dropNode.parent && dropNode.parent.data && dropNode.parent.data.pid) {
        respetPid = [dropNode.parent.data.pid];
      }
      this.addLoading = true;
      customerLevelSort(params).then((res) => {
        this.getData(respetPid);
        this.addLoading = false;
        res.code === 200 && this.$message.success('排序成功');
      }).catch(() => {
        this.getData(respetPid);
        this.addLoading = false;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.setting-main {
  border-top: 1px solid #EBEEFD;
  & ::v-deep {
    .el-tree {
      .el-tree-node {
        position: relative;
      }
      & > .el-tree-node {
        padding: 15px 1px;
        border-bottom: 1px solid #EBEEFD;
        position: relative;
        & > .el-tree-node__content {
          margin: 0;
        }
        &:nth-last-child(2) {
          border-bottom: none;
        }
      }
    }
    .el-tree-node__children {
      @include scrollBar(auto, hidden);
    }
    .el-tree-node__content {
      background-color: #fff;
      height: 32px;
      margin-top: 10px;
      &:hover {
        background-color: #fff;
      }
      &:last-child {
        margin-bottom: 10px;
      }
    }
    .el-tree-node__expand-icon {
      // display: none;
      height: 100%;
      visibility: hidden;
      padding: 0;
      position: absolute;
      left: -12px;
      top: 0px;
      transform: rotate(0deg) !important;
    }
  }
  .custom-tree-node {
    display: flex;
    align-items: center;
    width: 100%;
    font-size: 14px;
    .expend-btn {
      width:16px;
      height:16px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20px;
      .expend-icon {
        width: 16px;
        height: 16px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    .setting-btn-container {
      margin-left: 20px;
      display: flex;
      min-width: 114px;
      align-items: center;
      .btn {
        margin-left: 10px;
        color: #406eff;
        cursor: pointer;
      }
    }
    .is-draggable {
      cursor: move;
    }
    .tree-main {
      font-size: 14px;
      font-family:PingFangSC-Regular,PingFang SC;
      font-weight:400;
      color:rgba(102,102,102,1);
      line-height:16px;
      text-overflow: ellipsis;
      flex: 1;
      .tree-content {
        display: flex;
        align-items: center;
        max-width: 1500px;
        .label-text {
          color: #999;
        }
        .tree-content-cell {
          display: flex;
          align-items: center;
          flex: 1;
          width: 180px;
        }
        .width-240 {
          min-width: 240px !important;
        }
        .level-name-bg {
          padding: 0 10px;
          border-radius: 999px;
          display: inline-block;
          height: 20px;
          line-height: 20px;
        }
      }
      .cell-input {
        width: 100px;
        & ::v-deep {
          .el-input__inner {
            width: 100px;
          }
          .el-input__suffix {
            line-height: 32px;
            cursor: default;
          }
        }
      }
      .auto-width-input{
        min-width: 100px;
        max-width: 180px;
        margin-right: 6px;
        .el-input__inner {
          width: 100% !important;
        }
      }
      .post-select {
        & ::v-deep {
          .el-select__tags {
            flex-wrap: nowrap;
            .el-tag > span {
              min-width: 20px !important;
              max-width: 37px !important;
            }
            .el-tag.el-tag--info:last-child {
              padding-left: 1px;
              padding-right: 1px;
              margin-left: 4px;
            }
            .el-tag.el-tag--info .el-tag__close {
              right: -2px !important;
              top: 1px !important;
            }
          }
        }
      }
    }
  }
}
</style>
